const { init } = require('./../../wxCloudClientSDK.umd.js')
// 指定云开发环境 ID
wx.cloud.init({
  env: "cloud1-9gel6ndh8e555155", // 当前的云开发环境 ID
});
    
const client = init(wx.cloud);

Page({
  data: {
    searchValue: '',
    categories: [],
    currentCategory: 1,
    recommendGoods: [{
      id: 1,
      name: '武汉尚小镜内镜诊疗医院',
      title: '家庭卡',
      price: 96,
      image: 'cloud://cloud1-9gel6ndh8e555155.636c-cloud1-9gel6ndh8e555155-1345681178/home_card.jpg'
    }],
    products: [],
    // 当前选中的分类ID
    activeCategoryId: 1,
    // 商品分类数据
    categories1: [],
    // 商品列表数据
    products1: [],
    page: 1,   // 当前页码
    pageSize: 10,  // 每页数据量
    productPage: 1,  // 商品列表当前页码
    productPageSize: 5,  // 商品列表每页数据量
    loading: false,  // 是否正在加载
    noMoreData: false,  // 是否没有更多数据
  },

  onLoad() {
    this.queryCategoryInfo();
  },

  queryCategoryInfo() {
    client.models.category_info.list({
      filter: {
        where: {
         $and: [{
           parentId: {
             $eq: 0
           },
         },
       ],
        },
        order: ['sortOrder ASC']
      },
      pageSize: this.data.pageSize,
      pageNumber: this.data.page,
      getCount: true
    }).then(res => {
    
     this.parseCategoryData(res.data.records);

     if (res.data.records.length > 0) {
      const categoryId = res.data.records[0].categoryId;
      this.loadProducts(categoryId);
      this.setData({
        activeCategoryId: categoryId
      });
    }
   }).catch(res => {
     console.log("category_info err: " + res)
   });
  },

  parseCategoryData(records) {
    const parsedData = records.map(item => {
      return {
        id: item.categoryId,
        categoryId: item.categoryId,
        name: item.categoryName,
      };
    });

    this.setData({
      categories1: parsedData
    });
  },

  onSearch(e) {
    this.setData({
      searchValue: e.detail.value
    })
  },


  goToProductDetail(e) {
    const id = e.currentTarget.dataset.id;
    console.log("id: " + id);
    wx.navigateTo({
      url: '/page/productdetail/index?param1=' + id,
    })
  },

  // 点击分类事件
  onCategoryTap(e) {
    const categoryId = e.currentTarget.dataset.id;

    console.log("categoryId: " + categoryId);

    this.setData({
      activeCategoryId: categoryId,
      products1: [],
      productPage: 1,   // 当前页码
      productPageSize: 5,  // 每页数据量
      loading: false,  // 是否正在加载
      noMoreData: false,  // 是否没有更多数据
    });
    // 这里可以根据 categoryId 请求对应的商品列表
    this.loadProducts(categoryId);
  },

  // 模拟加载商品列表
  loadProducts(categoryId) {

    console.log("categoryId: " + categoryId + "; loading: " + this.data.loading + "; noMoreData: " + this.data.noMoreData);

    if (this.data.loading || this.data.noMoreData) return;  // 防止重复加载

    this.setData({ loading: true });
    
    this.queryProductInfos(categoryId, this.data.productPage, this.data.productPageSize);
      
  },

  queryProductInfos(categoryId, productPage, productPageSize) {
      client.models.product_info.list({
        filter: {
          where: {
          $and: [{
            categoryId: {
              $eq: categoryId
            },
          },
        ],
          },
          order: ['categoryId ASC']
        },
        pageSize: productPageSize,
        pageNumber: productPage,
        getCount: true
      }).then(res => {
      console.log("product_info: " + res.data.records);
      
      if (res.data?.records?.length > 0) {
        this.parseProductData(res.data.records);

        this.setData({
          productPage: this.data.productPage + 1,  // 页码加1
        });
      } else {
        this.setData({
          noMoreData: true,     // 没有更多数据
        });
      }

      this.setData({ loading: false });

    }).catch(res => {
      console.log("product_info err: " + res)
    });
  },


  parseProductData(data) {
    const parsedData = data.map(item => {
      return {
        id: item._id,
        productId: item.productId,
        name: item.productName,
        price: item.price,
        image: item.images.url,
      };
    });

    this.setData({
      products1: this.data.products1.concat(parsedData)
    });
  },

  // 监听页面滚动到底部
  onReachBottom() {
    this.loadProducts(this.data.activeCategoryId);
  },
});